package edu.umuc.cmsc495_final_project;

/*
 // if I have time I will switch our system over to a REAL database hosted in google cloud
 import com.google.appengine.api.rdbms.AppEngineDriver;  
 import java.io.IOException; 
 import java.sql.*; 
 import javax.servlet.http.HttpServletRequest; 
 import javax.servlet.http.HttpServletResponse;
 */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.logging.Level;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;

public class application implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8209769703455418665L;

	//
	DataBase db;

	//
	JFrame frame;
	JFrame settings;

	private managerGUI managerFrame;
	private hostessGUI hostessFrame;
	private kitchenGUI kitchenFrame;
	private serverGUI serverFrame;
	private barGUI barFrame;

	//
	JPanel drinks;
	JPanel beer;
	JPanel wine;
	JPanel alcohol;
	JPanel appatizers;
	JPanel sides;
	JPanel entrees;
	JPanel dessert;
	JPanel misc;

	//
	keypadPanel kp;
	titlePanel tp;

	//
	JButton shutdownProgram = null;
	JButton settingsButton = null;

	//
	employee currentUser;
	employee currentManager;

	//
	boolean managerOverride = false;
	boolean inBar = false;

	//
	Verification vp;

	//
	int panelWidth;
	int panelHeight;
	int currentSeatSelected;
	double tempTicketCost = 0.0;

	//
	String tempTicketArea = "";

	//
	ArrayList<JButton> stoolButtons = new ArrayList<JButton>();
	ArrayList<JButton> tableButtons = new ArrayList<JButton>();

	//
	Font font = new Font("Verdana", Font.BOLD, 40);

	//
	DecimalFormat myFormatter = new DecimalFormat("$###,###.##");

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					// Sets look and feel of local system
					UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					// create application window
					application window = new application();
					// Set main frame visible
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public application() {

		screenSize ss = new screenSize();

		panelWidth = ss.getScreenWidth();
		panelHeight = ss.getScreenHeight();

		// open previous db
		try {
			// use buffering
			FileInputStream file = new FileInputStream("TeamB_Database.db");
			InputStream buffer = new BufferedInputStream(file);
			ObjectInputStream input = new ObjectInputStream(buffer);
			try {
				Object obj = input.readObject();

				if (obj instanceof DataBase)
					db = (DataBase) obj;

				System.out.println("Object opened is: " + db);

			} finally {
				input.close();
			}
		} catch (ClassNotFoundException ex) {
			System.err.printf(Level.SEVERE + " Cannot perform input. Class not found.", ex);

			db = new DataBase();
			addDEFAULTDEMOITEMS();
		} catch (IOException ex) {
			System.err.println("Cannot perform input." + ex);

			db = new DataBase();
			addDEFAULTDEMOITEMS();
		} catch (Exception ex) {

			db = new DataBase();
			addDEFAULTDEMOITEMS();
		}

		// setup gui and system components
		initialize();
	}

	private void addDEFAULTDEMOITEMS() {
		// DEMO content
		// ////////////////////////////////////////////////////////////////////////////////

		// add employees to roster
		db.addNewEmployee(new employee("doe", "john", "0000", credential.ADMINISTRATOR, 1111));
		db.addNewEmployee(new employee("doe", "jane", "0001", credential.BARTENDER, 2222));
		db.addNewEmployee(new employee("allover", "jill", "0002", credential.CHEF, 3333));
		db.addNewEmployee(new employee("daniels", "jack", "0003", credential.COOK, 4444));
		db.addNewEmployee(new employee("dickerson", "darrel", "0004", credential.HOSTESS, 5555));
		db.addNewEmployee(new employee("barron", "kevin", "0005", credential.MANAGER, 6666));
		db.addNewEmployee(new employee("washington", "marry", "0006", credential.SERVER, 7777));

		// set hours of operation
		db.setHoursOfOp(new RestaurantTime(12, 00), new RestaurantTime(24, 30)); // hours,
																					// min
																					// (24
																					// hour
																					// time)

		System.out.println(db.getHoursOfOp());
		// set tax rate
		db.setTaxRate(.06);

		// add food/drinks to menu
		db.addItems(new Items("Water \"Bottled\"", ItemType.DRINK, 2));
		db.addItems(new Items("Water \"Tap\"", ItemType.DRINK, 0));
		db.addItems(new Items("Coke", ItemType.DRINK, 2.50));
		db.addItems(new Items("Sprite", ItemType.DRINK, 2.50));
		db.addItems(new Items("Dr. Pepper", ItemType.DRINK, 2.50));
		db.addItems(new Items("Orange", ItemType.DRINK, 2.50));
		db.addItems(new Items("Orange Juice", ItemType.DRINK, 2.50));
		db.addItems(new Items("Milk", ItemType.DRINK, 2.50));
		db.addItems(new Items("Fries", ItemType.APPATIZER, 4.99));
		db.addItems(new Items("Onion Rings", ItemType.APPATIZER, 4.99));
		db.addItems(new Items("Cheese Cake", ItemType.DESSERT, 8.99));
		db.addItems(new Items("Lemonchello", ItemType.DESSERT, 5.99));
		db.addItems(new Items("16oz Sirlion Steak", ItemType.ENTREE, 28.99));
		db.addItems(new Items("Lobster Tail", ItemType.ENTREE, 32.99));
		db.addItems(new Items("Ceasar Salad", ItemType.SIDE, 6.99));
		db.addItems(new Items("White - Riesling", ItemType.WINE, 5.99));
		db.addItems(new Items("Red - Merlot", ItemType.WINE, 5.99));
		db.addItems(new Items("Coors lite \"On-tap\"", ItemType.BEER, 3.99));
		db.addItems(new Items("Coors lite \"Bottle\"", ItemType.BEER, 4.50));
		db.addItems(new Items("Bacardi Vodka - Plain", ItemType.ALCOHOL, 5));
		db.addItems(new Items("Patron Tecquila", ItemType.ALCOHOL, 5));

		// add tables to seating area
		for (int i = 0; i < 10; i++)
			db.addNewTable(new Table(i, TableType.EIGHT_PERSON_RECT, DinnerEvent.AVAILABLE));

		// add bar stools to bar
		for (int i = 0; i < 6; i++)
			db.addNewBarStool(new Table(i, TableType.BAR_STOOL, DinnerEvent.AVAILABLE));
		// //////////////////////////////////////////////////////////////////////////////////
	}

	/**
	 * Initialize the contents of the frame.
	 */
	public void initialize() {
		// establish main application background frame
		frame = new JFrame();
		frame.setTitle("Team B - Restaurant POS System");
		frame.setExtendedState(Frame.MAXIMIZED_BOTH);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setUndecorated(true);
		frame.setLayout(null);

		// Background pane Buttons
		// exit button
		shutdownProgram = new JButton("Shutdown");
		shutdownProgram.setBounds(15, panelHeight - 145, 150, 130);
		shutdownProgram.setVisible(true);
		frame.add(shutdownProgram);
		shutdownProgram.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				try {
					System.out.println("Attempting to export the current database");
					// use buffering
					FileOutputStream file = new FileOutputStream("TeamB_Database.db");
					OutputStream buffer = new BufferedOutputStream(file);
					ObjectOutputStream output = new ObjectOutputStream(buffer);
					try {
						output.writeObject((DataBase) db);
					} finally {
						output.close();
					}
				} catch (IOException ex) {
					System.err.printf(Level.SEVERE + " Cannot perform output.", ex);
				}

				System.out.println("Exiting application");
				System.exit(0);
			}
		});

		// settings button
		settingsButton = new JButton("Settings");
		settingsButton.setBounds(15, panelHeight - 290, 150, 130);
		frame.add(settingsButton);
		settingsButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				// new setting instance
				final Settings settings = new Settings(db);

				// load previous items
				settings.txtNotes1.setText(db.getNotes1());
				settings.txtNotes2.setText(db.getNotes2());
				settings.txtNotes3.setText(db.getNotes3());

				// save button actions
				settings.btnSave.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {

						// just in case no starting id has been established
						if (settings.empIDNum == null)
							settings.empIDNum = "";

						// save based on tab
						switch (settings.selectedpane) {
						case 0:
							break;
						case 1: { // administrators
							db.addNewEmployee(new employee(settings.lastName, settings.firstName, settings.generateEmpID(), credential.ADMINISTRATOR,
									settings.passkey));
							System.out.println("New administrator added");
							break;
						}
						case 2: { // employees
							db.addNewEmployee(new employee(settings.lastName, settings.firstName, settings.generateEmpID(), settings.privelageLevel,
									settings.passkey));
							System.out.println("New " + settings.privelageLevel + " employee added");
							break;
						}
						case 3: { // settings
							break;
						}
						case 4: { // notes
							db.addNotes1(settings.txtNotes1.getText());
							db.addNotes2(settings.txtNotes2.getText());
							db.addNotes3(settings.txtNotes3.getText());
							System.out.println("saved notes");
							break;
						}
						}

						// close frame on save, unless we have the above working
						settings.dispose();
					}
				});

				// backup database button
				settings.btnBackupDatabase.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						// TODO .. needs a good bit of work
						settings.fc = new JFileChooser();
						settings.fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

						int returnVal = settings.fc.showSaveDialog(settings);
						if (returnVal == JFileChooser.APPROVE_OPTION) {
							File file = settings.fc.getSelectedFile();

							new exportDB(file.getName());
						}
					}
				});

				// export database button
				 settings.btnExportDatabase.addActionListener(new ActionListener() { 
					 public void actionPerformed(ActionEvent arg0) {
						 settings.fc = new JFileChooser();
						 int returnVal = settings.fc.showSaveDialog(frame);
				            if (returnVal == JFileChooser.APPROVE_OPTION) {
				                String file = settings.fc.getSelectedFile().toString();
				                new exportDB(file);
				            } else {
				            	System.out.println("Save command cancelled by user.");
				            }
					 } 
				 });
				// new database button
				 settings.btnNewDatabase.addActionListener(new ActionListener() { 
					 public void actionPerformed(ActionEvent arg0) {
						 db = new DataBase();
					 } 
				 });
				// delete database button
				// TODO

				// save new tax rate button
				settings.btnSaveTaxRate.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg1) {
						System.out.println("change tax rate from " + db.getTaxRate());

						db.setTaxRate(settings.taxRate);

						System.out.println("Changed tax to " + db.getTaxRate());
						// go back to correct tab
						settings.tabbedPane.setComponentAt(3, settings.settings);
						settings.repaint();
					}
				});

				// save new hours of operation button
				settings.btnSaveHoursOfOp.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg1) {
						System.out.println("change hours of operation");

						db.setHoursOfOp(settings.hoursOfOpOpen, settings.hoursOfOpClose);
						db.setHoursOfOp(new RestaurantTime(settings.hoursStart, settings.minStart), new RestaurantTime(settings.hoursEnd,
								settings.minEnd));
						// System.out.println("hours should be " +
						// settings.getHoursStart() + " " +
						// settings.getHoursEnd());
						// System.out.println("minutes should be " +
						// settings.getMinStart() + " " + settings.getMinEnd());

						System.out.println("hours of op are " + db.getHoursOfOp());
						// go back to correct tab
						settings.tabbedPane.setComponentAt(3, settings.settings);
						settings.repaint();
					}
				});

				// add new tables/chair button
				settings.btnMakeTable.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg1) {
						System.out.println("make new table/chair");

						// create tables/stools
						for (int i = 0; i < settings.tableQuant; i++) {
							System.out.println(i + " " + settings.getTable().getTableType());

							// add bar stool, if seat is bar stool, otherwise
							// only add a restaurant table
							if (settings.getTable().getTableType() == TableType.BAR_STOOL)
								db.addNewBarStool(settings.getTable());
							else
								db.addNewTable(settings.getTable());
						}
						// go back to correct tab
						settings.tabbedPane.setComponentAt(3, settings.settings);
						settings.repaint();
					}
				});

				// remove table/chair button
				settings.btnRemoveTable.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg1) {

						System.out.println("remove tables/chairs");

						// create tables/stools
						for (int i = 0; i < settings.tableQuant; i++) {
							System.out.println(i + " " + settings.getTable().getTableType());

							// add bar stool, if seat is bar stool, otherwise
							// only add a restaurant table
							if (settings.getTable().getTableType() == TableType.BAR_STOOL)
								db.removeBarStool(settings.getTable());
							else
								db.removeTable(settings.getTable());
						}
						// go back to correct tab
						settings.tabbedPane.setComponentAt(3, settings.settings);
						settings.repaint();
					}
				});

				//

				// used to bring the keypad back after closing the settings
				// window
				settings.addWindowListener(new WindowListener() {
					@Override
					public void windowActivated(WindowEvent e) {
						try {
							// close any existing keypads
							getKp().dispose();
						} catch (Exception ex) {
							System.err.println("Error closing keypad");
						}
					}

					@Override
					public void windowClosed(WindowEvent e) {
						try {
							// close any existing keypads
							getKp().dispose();
						} catch (Exception ex) {
							System.err.println("Error Closing keypad");
						}

						// bring keypad layer to front for next login attempt
						openKeyPad();
					}

					@Override
					public void windowClosing(WindowEvent e) {
					}

					@Override
					public void windowDeactivated(WindowEvent e) {
					}

					@Override
					public void windowDeiconified(WindowEvent e) {
					}

					@Override
					public void windowIconified(WindowEvent e) {
					}

					@Override
					public void windowOpened(WindowEvent e) {
					}
				});
			}
		});

		openKeyPad();
	}

	// check if user is a manager
	protected boolean isManager() {
		if (currentUser.getPrivelageLevel().equals(credential.ADMINISTRATOR) || currentUser.getPrivelageLevel().equals(credential.MANAGER))
			return true;
		else
			return false;
	}

	// keypad frame
	protected void openKeyPad() {
		// keypad frame and layer pane
		setKp(new keypadPanel(db));

		getKp().doneButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				// temp user passkey storage
				String passkey = getKp().getPasskey();

				// establish verification link
				vp = new Verification(db, passkey);

				// if users validated
				if (vp.isValid()) {
					// check to see if current user is logged in -- is this a
					// manager override?
					if (managerOverride) {
						// open title bar as manager or user
						if (vp.getEmp().getPrivelageLevel() == credential.MANAGER || vp.getEmp().getPrivelageLevel() == credential.ADMINISTRATOR) {
							try {
								// close old title bar
								tp.dispose();
							} catch (Exception e) {
								System.err.println("Error in closing title panel");
							}

							// updates user information for title bar
							userStatus();

							// open new instance of title bar
							titleBar(true);
						}
					} else {

						// updates user information for title bar
						userStatus();

						// open title bar as manager or user
						if (isManager())
							titleBar(true);
						else
							titleBar(false);

						// establish correct frame values
						try {
							openFrame(vp.getEmp().getPrivelageLevel());
						} catch (Exception e) {
							System.err.println("Error opening user module frame");
						}
					}
					// close the keypad
					getKp().dispose();
				}

				// resets keypad values
				getKp().reset();
			}
		});
	}

	// title bar
	protected void titleBar(boolean manager) {
		tp = new titlePanel(manager);

		// manager override button
		try {
			tp.managerOverride.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					// alter the state to include manager privileges
					System.out.println("clicked on manager override button");
					managerOverride = true;

					openKeyPad();
				}
			});
		} catch (NullPointerException npe) {
			System.err.println("manager override not functioning");
		}

		// global logout
		try {
			tp.logout.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					// check is manager
					if (vp.getEmp().getPrivelageLevel() == credential.MANAGER || vp.getEmp().getPrivelageLevel() == credential.ADMINISTRATOR) {
						try {
							barFrame.dispose();
						} catch (Exception e) {
						}
						try {
							kitchenFrame.dispose();
						} catch (Exception e) {
						}
						try {
							hostessFrame.dispose();
						} catch (Exception e) {
						}
						try {
							serverFrame.dispose();
						} catch (Exception e) {
						}
						try {
							// TODO if I have time.. make this so that the
							// manager isnt logged out completely.

							// log off existing user account
							currentUser.setLoggedIn(false);

							// close all user gui related items including title
							// panel
							tp.dispose();
							closeFrame();

							// bring keypad layer to front for next login
							// attempt
							openKeyPad();

							// unhide settings and shutdown
							shutdownProgram.setVisible(true);
							settingsButton.setVisible(true);

						} catch (Exception e) {
						}
					}
					// reset override if active
					else if (managerOverride) {
						System.out.println("logging off of manager override");
						managerOverride = false;

						// close manager/user title panel
						tp.dispose();

						// open normal title panel again
						titleBar(managerOverride);
					} else {
						// log off existing user account
						currentUser.setLoggedIn(false);

						// close all user gui related items including title
						// panel
						tp.dispose();
						closeFrame();

						// bring keypad layer to front for next login attempt
						openKeyPad();

						// unhide settings and shutdown
						shutdownProgram.setVisible(true);
						settingsButton.setVisible(true);
					}
				}
			});
		} catch (NullPointerException npe) {
			System.err.println("loggout not functioning");
		}

		// check if this is a manager override
		if (managerOverride) {
			tp.setCurrentUser("#" + currentManager.getIdNum() + "-" + currentManager.getLastname() + "/", currentUser.getPrivelageLevel(),
					currentManager.getPrivelageLevel());

		} else {
			// send updated title bar data
			tp.setCurrentUser("#" + currentUser.getIdNum() + "-" + currentUser.getLastname(), currentUser.getPrivelageLevel());
		}

		// lets title know if user is a manager
		// tp.setManagerState(isManager());

		// make sure its visible
		tp.setVisible(true);
	}

	// user status
	protected void userStatus() {
		if (managerOverride) {
			//
			currentManager = vp.getEmp();

			// manager can be logged into multiple PC's, users cannot
		} else {
			// setup current user
			currentUser = vp.getEmp();

			// is user logged in already
			try {
				if (currentUser.isLoggedIn()) {
					// Open a popup dialog saying they are already logged in
					// else
					// where and reopen keypad if not already logged in
					System.out.println("User: #" + currentUser.getIdNum() + "-" + currentUser.getLastname() + ", is already logged in.");
				} else
					currentUser.setLoggedIn(true);
			} catch (NullPointerException npe) {
				System.err.println("user status login error");
			}
		}
	}

	// opens correct frame
	protected void openFrame(credential privelage) {

		System.out.println("User should be " + privelage + " and should open yes ");

		// establish frame
		switch (privelage) {
		case ADMINISTRATOR: // administrator
		case MANAGER: { // manager

			managerFrame = new managerGUI();
			{
				managerFrame.hostess.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						System.out.println("hit hostess frame button");
						openFrame(credential.HOSTESS);
					}
				});

				managerFrame.kitchen.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						System.out.println("hit kitchen frame button");
						openFrame(credential.CHEF);
					}
				});

				managerFrame.bar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						System.out.println("hit hostess frame button");
						openFrame(credential.BARTENDER);
					}
				});

				managerFrame.server.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						System.out.println("hit hostess frame button");
						openFrame(credential.SERVER);
					}
				});

				// managerFrame.splitPane.setRightComponent(new
				// OpenTablesPanel(db));
			}
			break;
		}
		case HOSTESS: { // hostess
			hostessFrame = new hostessGUI();

			// add table to server pane seating area
			//addTables((hostessGUI) hostessFrame, hostessFrame.tablePane);
						
			// addTables(hostessFrame);
			hostessFrame.newReservation.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					final newDiner diner = new newDiner(db);

					diner.btnMakeReservation.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							//
							db.addNewPatron(diner.getDiner());

							// create current time
							hostessFrame.time = new DefaultMutableTreeNode(new RestaurantTime().getCurrentTime());

							switch (diner.getDiner().getDineType()) {
							case RESERVATION: {
								hostessFrame.reservation.add(hostessFrame.time);
								hostessFrame.time.add(new DefaultMutableTreeNode(diner.getDiner()));
								break;
							}
							case WALKIN: {
								hostessFrame.walkin.add(hostessFrame.time);
								hostessFrame.time.add(new DefaultMutableTreeNode(diner.getDiner()));
								break;
							}
							case BAR: {
								hostessFrame.bar.add(hostessFrame.time);
								hostessFrame.time.add(new DefaultMutableTreeNode(diner.getDiner()));
								break;
							}
							}

							hostessFrame.patronWaitTree.repaint();

							System.out.println(diner.getDiner());
							diner.close();
						}
					});
				}
			});
			break;
		}
		case CHEF: // kitchen
		case COOK: { // chef
			kitchenFrame = new kitchenGUI();
			break;
		}
		case BARTENDER: { // bartender
			barFrame = new barGUI();

			// add items to bar pane menu
			addFoodItems(barFrame.orderPane);

			// add stools to bar pane seating area
			addStools((barGUI) barFrame, barFrame.stoolPane);

			// action listener for new guest
			barFrame.newGuest.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// ....
					System.out.println("stool " + currentSeatSelected + " is now taken " + db.getBarStools().get(currentSeatSelected).isTableTaken());
					//
					String tempGuest = JOptionPane.showInputDialog("Name of guess");
					patron tempPatron = new patron(tempGuest, DineType.BAR, null, 1, true);
					db.addNewPatron(tempPatron);

					db.getBarStools().get(currentSeatSelected).setDinnerEvent(DinnerEvent.JUST_SEATED);
					stoolButtons.get(currentSeatSelected).setBackground(Color.YELLOW); 
					db.getBarStools().get(currentSeatSelected).setTableTaken(true);
					db.getBarStools().get(currentSeatSelected).setWhosSeatedHere(tempPatron);

					barFrame.newGuest.setEnabled(false);

					System.out.println("this person should be in this seat " + db.getBarStools().get(currentSeatSelected).getWhosSeatedHere());
					
				}
			});

			barFrame.closeTicket.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Close ticket for " + db.getBarStools().get(currentSeatSelected).getWhosSeatedHere());

					db.getBarStools().get(currentSeatSelected).getWhosSeatedHere().setTicketClosed(true);

					db.getBarStools().get(currentSeatSelected).setDinnerEvent(DinnerEvent.AVAILABLE);
					stoolButtons.get(currentSeatSelected).setBackground(Color.GREEN); 
					db.getBarStools().get(currentSeatSelected).setTableTaken(false);
					db.getBarStools().get(currentSeatSelected).setWhosSeatedHere(null);
					
					barFrame.txtAreaReceipt.setText("");
					barFrame.fldReceiptTot.setText("");
					
				}
			});

			barFrame.stoolPane.repaint();
			break;
		}
		case SERVER: { // server
			serverFrame = new serverGUI();
			
			// add items to server pane menu
			addFoodItems(serverFrame.orderPane);

			// add table to server pane seating area
			addTables((serverGUI) serverFrame, serverFrame.tablePane);

			// action listener for new guest
			serverFrame.newGuest.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// ....
					System.out.println("table " + currentSeatSelected + " is now taken " + db.getTables().get(currentSeatSelected).isTableTaken());
					//
					String tempGuest = JOptionPane.showInputDialog("Name of guess");
					patron tempPatron = new patron(tempGuest, DineType.RESERVATION, null, 1, true);
					db.addNewPatron(tempPatron);

					db.getTables().get(currentSeatSelected).setDinnerEvent(DinnerEvent.JUST_SEATED);
					tableButtons.get(currentSeatSelected).setBackground(Color.YELLOW);
					db.getTables().get(currentSeatSelected).setTableTaken(true);
					db.getTables().get(currentSeatSelected).setWhosSeatedHere(tempPatron);

					serverFrame.newGuest.setEnabled(false);

					System.out.println("this person should be in this seat " + db.getTables().get(currentSeatSelected).getWhosSeatedHere());
				}
			});

			serverFrame.closeTicket.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Close ticket for " + db.getTables().get(currentSeatSelected).getWhosSeatedHere());

					db.getTables().get(currentSeatSelected).getWhosSeatedHere().setTicketClosed(true);

					db.getTables().get(currentSeatSelected).setDinnerEvent(DinnerEvent.AVAILABLE);
					tableButtons.get(currentSeatSelected).setBackground(Color.GREEN); 
					db.getTables().get(currentSeatSelected).setTableTaken(false);
					db.getTables().get(currentSeatSelected).setWhosSeatedHere(null);
					
					serverFrame.txtAreaReceipt.setText("");
					serverFrame.fldReceiptTot.setText("");
				}
			});

			break;
		}
		}
	}

	// opens correct frame
	protected void closeFrame() {

		// establish frame
		switch (currentUser.getPrivelageLevel()) {// privelage) {
		case ADMINISTRATOR: // administrator
		case MANAGER: { // manager
			managerFrame.dispose();
			break;
		}
		case HOSTESS: { // hostess
			hostessFrame.dispose();
			break;
		}
		case CHEF: // kitchen
		case COOK: { // chef
			kitchenFrame.dispose();
			break;
		}
		case BARTENDER: { // bartender
			barFrame.dispose();
			break;
		}
		case SERVER: { // server
			serverFrame.dispose();
			break;
		}
		}
	}

	//
	public keypadPanel getKp() {
		return kp;
	}

	//
	public void setKp(keypadPanel kp) {
		this.kp = kp;
	}

	//
	public void addStools(JFrame frame, JPanel panel) {
		System.out.println("Add stools now");

		try {
			// read in all items on menu
			for (int i = 0; i < db.getBarStools().size(); i++) {

				Table tempStool1 = db.getBarStools().get(i);

				String tempTableID = "Stool " + String.valueOf(tempStool1.getTableID());
				String tempSeats = "Seats 1";

				// add button for
				JButton tempButton = new JButton(new StoolButtonAction(i, (barGUI) frame));

				// color code where the table is at
				switch (tempStool1.getDinnerEvent()) {

				case AVAILABLE: {
					tempButton.setBackground(Color.GREEN); // GREEN
					break;
				}
				case JUST_SEATED: {
					tempButton.setBackground(Color.YELLOW); // YELLOW
					break;
				}
				case EATING: {
					tempButton.setBackground(Color.RED); // RED
					break;
				}
				case FINISHING: {
					tempButton.setBackground(Color.ORANGE); // ORANGE
					break;
				}
				}

				tempButton.setLayout(new BorderLayout());
				JLabel label1 = new JLabel(tempTableID, JLabel.CENTER);
				label1.setFont(font);
				JLabel label2 = new JLabel(tempSeats, JLabel.CENTER);
				label2.setFont(font);
				tempButton.add(BorderLayout.NORTH, label1);
				tempButton.add(BorderLayout.SOUTH, label2);
				tempButton.setAction(new StoolButtonAction(i, (barGUI) frame));
				// tempButton.addFocusListener(this);

				switch (db.getBarStools().get(i).getTableType()) {
				case BAR_STOOL: {
					stoolButtons.add(i, tempButton);
					panel.add(tempButton);
					break;
				}
				}
			}
		} catch (Exception e) {
			System.err.println("Error adding new tables/chairs to db");
		}
		System.out.println("There is " + db.getTables().size() + " bar stools available to sit at ");
	}

	// Menu item action listener
	class StoolButtonAction extends AbstractAction {
		int num;
		barGUI frame;

		public StoolButtonAction(int num, barGUI frame) {
			this.num = num;
			this.frame = frame;
		}

		public void actionPerformed(ActionEvent e) {
			System.out.println("You clicked the button - Stool is " + db.getBarStools().get(num).getTableID());

			// check if stool is available
			if (!db.getBarStools().get(num).isTableTaken()) {
				System.out.println("This table is available");
				// enable seat guest button
				frame.newGuest.setEnabled(true);
				currentSeatSelected = num;
				tempTicketArea = "";
				tempTicketCost = 0.0;
				frame.txtAreaReceipt.setText("");
				frame.fldReceiptTot.setText("");
			} else {
				System.out.println("This table is NOT available");
				System.out.println(db.getBarStools().get(num).getWhosSeatedHere() + " is seated here");

				inBar = true;
				
				// temp variable for all items in ticket
				ArrayList<Items> tempTicket = db.getBarStools().get(num).getWhosSeatedHere().getTicket();

				tempTicketCost = 0.0;
				tempTicketArea = "";
				for (int i = 0; i < tempTicket.size(); i++) {
					tempTicketArea += i + " - " + tempTicket.get(i) + " \n";
					tempTicketCost += tempTicket.get(i).getPrice();
				}
				frame.txtAreaReceipt.setText(tempTicketArea);
				frame.fldReceiptTot.setText(String.valueOf(myFormatter.format(tempTicketCost)));

				currentSeatSelected = num;
				frame.newGuest.setEnabled(false);
			}
		}

		public void focusGained(FocusEvent arg0) {
			//
		}

		public void focusLost(FocusEvent arg0) {
			frame.newGuest.setEnabled(false);
		}
	}

	//
	public void addTables(JFrame frame, JPanel panel) {

		System.out.println("Add tables now");

		try {
			// read in all items on menu
			for (int i = 0; i < db.getTables().size(); i++) {

				Table tempTable1 = db.getTables().get(i);

				String tempTableID = "Table " + String.valueOf(tempTable1.getTableID());
				String tempSeats = "Seats " + tempTable1.getTableType().toString().substring(0, 1);

				// add button for
				JButton tempButton = new JButton(new TableButtonAction(i, (serverGUI) frame));

				// color code where the table is at
				switch (tempTable1.getDinnerEvent()) {
				case AVAILABLE: {
					tempButton.setBackground(Color.GREEN); // GREEN
					break;
				}
				case JUST_SEATED: {
					tempButton.setBackground(Color.YELLOW); // YELLOW
					break;
				}
				case EATING: {
					tempButton.setBackground(Color.RED); // RED
					break;
				}
				case FINISHING: {
					tempButton.setBackground(Color.ORANGE); // ORANGE
					break;
				}
				}

				tempButton.setLayout(new BorderLayout());
				JLabel label1 = new JLabel(tempTableID, JLabel.CENTER);
				label1.setFont(font);
				JLabel label2 = new JLabel(tempSeats, JLabel.CENTER);
				label2.setFont(font);
				tempButton.add(BorderLayout.NORTH, label1);
				tempButton.add(BorderLayout.SOUTH, label2);
				tempButton.setAction(new TableButtonAction(i, (serverGUI) frame));

				switch (db.getTables().get(i).getTableType()) {

				case BAR_STOOL: {
					tableButtons.add(i, tempButton);
					panel.add(tempButton);
					break;
				}
				case TWO_PERSON_ROUND:
				case FOUR_PERSON_ROUND:
				case SIX_PERSON_ROUND:
				case TWO_PERSON_RECT:
				case FOUR_PERSON_RECT:
				case SIX_PERSON_RECT:
				case EIGHT_PERSON_RECT: {
					panel.add(tempButton);
					break;
				}
				}
			}
		} catch (Exception e) {
			System.err.println("Error adding new tables/chairs to db");
		}
		System.out.println("There is " + db.getTables().size() + " tables available to sit at ");
	}

	// Menu item action listener
	class TableButtonAction extends AbstractAction {
		int num;
		serverGUI frame;

		public TableButtonAction(int num, serverGUI frame) {
			this.num = num;
			this.frame = frame;
		}

		public void actionPerformed(ActionEvent e) {
			System.out.println("You clicked the button - Table is " + db.getTables().get(num).getTableID());

			// check if stool is available
			if (!db.getTables().get(num).isTableTaken()) {
				System.out.println("This table is available");
				// enable seat guest button
				frame.newGuest.setEnabled(true);
				currentSeatSelected = num;
				tempTicketArea = "";
				tempTicketCost = 0.0;
				frame.txtAreaReceipt.setText("");
				frame.fldReceiptTot.setText("");
			} else {
				System.out.println("This table is NOT available");
				System.out.println(db.getTables().get(num).getWhosSeatedHere() + " is seated here");

				inBar = false;
				
				// temp variable for all items in ticket
				ArrayList<Items> tempTicket = db.getTables().get(num).getWhosSeatedHere().getTicket();

				tempTicketCost = 0.0;
				tempTicketArea = "";
				for (int i = 0; i < tempTicket.size(); i++) {
					tempTicketArea += i + " - " + tempTicket.get(i) + " \n";
					tempTicketCost += tempTicket.get(i).getPrice();
				}
				frame.txtAreaReceipt.setText(tempTicketArea);
				frame.fldReceiptTot.setText(String.valueOf(myFormatter.format(tempTicketCost)));

				currentSeatSelected = num;
				frame.newGuest.setEnabled(false);
			}
		}

		public void focusGained(FocusEvent arg0) {
		}

		public void focusLost(FocusEvent arg0) {
		}
	}

	// add food items to menu panels
	public void addFoodItems(JPanel panel) {
		System.out.println("Add food items to menu");

		try {
			// Menu panes
			drinks = new JPanel(new FlowLayout());
			beer = new JPanel(new FlowLayout());
			wine = new JPanel(new FlowLayout());
			alcohol = new JPanel(new FlowLayout());
			appatizers = new JPanel(new FlowLayout());
			sides = new JPanel(new FlowLayout());
			entrees = new JPanel(new FlowLayout());
			dessert = new JPanel(new FlowLayout());
			misc = new JPanel(new FlowLayout());

			// create jpanels for menu
			JTabbedPane tabOrderPane = new JTabbedPane(JTabbedPane.TOP);
			panel.add(tabOrderPane, BorderLayout.CENTER);

			// add tabs to pane
			tabOrderPane.addTab("Non-Alcohol Drinks", drinks); // pane 0
			tabOrderPane.addTab("Beer", beer); // pane 1
			tabOrderPane.addTab("Wine", wine); // pane 2
			tabOrderPane.addTab("Alcohol", alcohol); // pane 3
			tabOrderPane.addTab("Appatizers", appatizers); // pane 4
			tabOrderPane.addTab("Sides", sides); // pane 5
			tabOrderPane.addTab("Entrees", entrees); // pane 6
			tabOrderPane.addTab("Dessert", dessert); // pane 7
			tabOrderPane.addTab("Misc", misc); // pane 8

			// read in all items on menu
			for (int i = 0; i < db.getItems().size(); i++) {

				Items tempItem1 = db.getItems().get(i);
				String price = String.valueOf(myFormatter.format(tempItem1.getPrice()));

				// add button for
				JButton tempButton = new JButton(new ItemButtonAction(i));
				tempButton.setLayout(new BorderLayout());
				JLabel label1 = new JLabel(tempItem1.getName(), JLabel.CENTER);
				label1.setFont(font);
				JLabel label2 = new JLabel(price, JLabel.CENTER);
				label2.setFont(font);
				tempButton.add(BorderLayout.NORTH, label1);
				tempButton.add(BorderLayout.SOUTH, label2);
				tempButton.setAction(new ItemButtonAction(i));

				switch (db.getItems().get(i).getType()) {

				case DESSERT: { // pane 7
					dessert.add(tempButton);
					break;
				}
				case APPATIZER: { // pane 4
					appatizers.add(tempButton);
					break;
				}
				case SIDE: { // pane 5
					sides.add(tempButton);
					break;
				}
				case ENTREE: { // pane 6
					entrees.add(tempButton);
					break;
				}
				case DRINK: { // pane 0
					drinks.add(tempButton);
					break;
				}
				case BEER: { // pane 1
					beer.add(tempButton);
					break;
				}
				case ALCOHOL: { // pane 3
					alcohol.add(tempButton);
					break;
				}
				case WINE: { // pane 2
					wine.add(tempButton);
					break;
				}
				case MISC: { // pane 8
					misc.add(tempButton);
					break;
				}
				}
			}

		} catch (NullPointerException npe) {
			System.err.println("There was problem loading menu items");
		}
		System.out.println("There is " + db.getItems().size() + " items available for sale ");
	}

	// Menu item action listener
	class ItemButtonAction extends AbstractAction {
		int num;

		public ItemButtonAction(int num) {
			this.num = num;
		}

		public void actionPerformed(ActionEvent e) {
			System.out.println("You clicked the button - Item is " + db.getItems().get(num).getName());
			System.out.println("Price is " + db.getItems().get(num).getPrice());
			
			if(inBar){
				// if bar item or seated menu item
				db.getBarStools().get(currentSeatSelected).getWhosSeatedHere().addTicketItem(db.getItems().get(num));
				db.getBarStools().get(currentSeatSelected).setDinnerEvent(DinnerEvent.EATING);
				//db.getBarStools().get(currentSeatSelected).setBackground(Color.RED);
			}
			else{
				// 
				db.getTables().get(currentSeatSelected).getWhosSeatedHere().addTicketItem(db.getItems().get(num));
				db.getTables().get(currentSeatSelected).setDinnerEvent(DinnerEvent.EATING);
				//db.getTables().get(currentSeatSelected).setBackground(Color.RED);
			}
			
		}
	}
}